package com.ironman.mes.web;

import com.ironman.mes.annotation.Logging;
import com.ironman.mes.annotation.Whitelist;
import com.ironman.mes.entity.dataobject.BinlogMaster;
import com.ironman.mes.service.HelloService;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row;
import com.mybatisflex.core.row.RowUtil;
import lombok.extern.slf4j.Slf4j;
import org.noear.redisx.RedisClient;
import org.noear.solon.annotation.*;
import org.noear.solon.cache.jedis.RedisCacheService;
import org.noear.solon.core.event.EventBus;
import org.noear.solon.core.handle.UploadedFile;
import org.noear.solon.hotplug.PluginManager;

import java.io.File;
import java.io.IOException;

@Slf4j
@Controller
@Mapping("/demo")
public class DemoController {

    @Init
    public void init() {
        System.out.println("DemoController init");
    }

    @Destroy
    public void destroy() {
        System.out.println("DemoController destroy");
    }

    @Mapping("/hello")
    public String hello(@Param(defaultValue = "world") String name) {
        EventBus.subscribe(String.class, event -> {
            System.out.println(event);
        });
        EventBus.publish("hello chj");
        log.info("hello chj");
        return String.format("Hello %s!", name);
    }

    @Mapping("/stop")
    public String stop() {
        PluginManager.stop("ee");
        return "ok";
    }

    @Inject
    RedisCacheService redisCacheService;

    @Mapping("/cache")
    public String cache() {
        RedisClient redisClient = redisCacheService.client();
        redisClient.open(session -> {
            session.key("key1").set("val1");
        });
        return redisClient.openAndGet(session -> session.key("key1").get());
    }

    @Logging
    @Whitelist
    @Mapping("/db")
    public BinlogMaster db() {
        Row row = Db.selectOneBySql("select * from binlog_master where id = ?", "110886503307145216");
        return RowUtil.toEntity(row, BinlogMaster.class);
    }

    //文件上传
    @Post
    @Mapping(path = "/upload")
    public String upload(UploadedFile file) throws IOException {
        System.out.println(file);
        try {
            file.transferTo(new File(file.getName()));
        } finally {
            file.delete();
        }
        return file.getName();
    }

    @Inject
    HelloService helloService;

    @Mapping("hello2")
    public String hello2(String username) {
        return helloService.hello(username);
    }

    @Mapping("ex")
    public void ex() {
        throw new RuntimeException("ex");
    }
}